package xyz.jpcr.covid19app.Fragment;

import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.like.LikeButton;
import com.like.OnLikeListener;

import org.eazegraph.lib.charts.PieChart;
import org.eazegraph.lib.models.PieModel;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import xyz.jpcr.covid19app.Activity.CityWiseActivity;
import xyz.jpcr.covid19app.Api.ApiClient;
import xyz.jpcr.covid19app.CovidAppWidget;
import xyz.jpcr.covid19app.Model.Country.Cities;
import xyz.jpcr.covid19app.Model.Country.Country;
import xyz.jpcr.covid19app.Model.Country.CountryResults;
import xyz.jpcr.covid19app.Activity.ProvinceWiseActivity;
import xyz.jpcr.covid19app.R;
import xyz.jpcr.covid19app.Util.IDBHelper;
import xyz.jpcr.covid19app.Util.IDateUtil;
import xyz.jpcr.covid19app.Util.ILocationUtil;
import xyz.jpcr.covid19app.Util.ISendBroadcastUtil;
import xyz.jpcr.covid19app.Util.IStoreUtil;


public class CountryFragment extends Fragment {

    Context context;
    private boolean isOK = false, isrefresh = false;
    private ILocationUtil iLocationUtil;
    ProgressDialog progressDialog;
    TextView fragment_country_CurrentConfirmed, fragment_country_confirmed, fragment_country_suspected, fragment_country_deaths, fragment_country_Cured, fragment_country_clock, fragment_country_day;
    PieChart fragment_country_piechart;
    LinearLayout province_btn, city_btn;
    List<CountryResults> countryResultsList;
    CountryResults provinceResult;
    Cities cityResult;
    ArrayList<Cities> citiesList;
    String city = null, province = null, querycity = null;
    View view;
    ArrayList<CountryResults> results;
    SwipeRefreshLayout swipeRefreshLayout;
    LikeButton likeButton;
    IDBHelper idbHelper;


    public CountryFragment() {
    }


    public static CountryFragment newInstance() {
        CountryFragment fragment = new CountryFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_country, container, false);
        IDateUtil.getInstance();
        fragment_country_CurrentConfirmed = view.findViewById(R.id.fragment_country_CurrentConfirmed);
        fragment_country_confirmed = view.findViewById(R.id.fragment_country_confirmed);
        fragment_country_suspected = view.findViewById(R.id.fragment_country_suspected);
        fragment_country_deaths = view.findViewById(R.id.fragment_country_deaths);
        fragment_country_Cured = view.findViewById(R.id.fragment_country_Cured);
        fragment_country_clock = view.findViewById(R.id.fragment_country_clock);
        fragment_country_day = view.findViewById(R.id.fragment_country_day);
        fragment_country_piechart = view.findViewById(R.id.fragment_country_piechart);
        province_btn = view.findViewById(R.id.fragment_country_province_data);
        swipeRefreshLayout = view.findViewById(R.id.fragment_country_swipefreshlayout);

        context = getContext();
        showProgressDialog();
        iLocationUtil = ILocationUtil.getInstance(context);

        idbHelper = new IDBHelper(context);
        likeButton = view.findViewById(R.id.fragment_country_likebtn);
        likeButton.setOnLikeListener(new OnLikeListener() {
            @Override
            public void liked(LikeButton likeButton) {
                if(idbHelper.insert(querycity, cityResult.getCurrentConfirmedCount(), cityResult.getSuspectedCount(), cityResult.getCuredCount(), cityResult.getDeadCount(),cityResult.getConfirmedCount(), provinceResult.getUpdateTime())) {
                    ISendBroadcastUtil.getInstance().updateWidget(context);
                    Toast.makeText(context, context.getText(R.string.add_success), Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(context, context.getText(R.string.add_failed), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void unLiked(LikeButton likeButton) {
                if(idbHelper.delete(querycity)) {
                    ISendBroadcastUtil.getInstance().updateWidget(context);
                    Toast.makeText(context, context.getText(R.string.cancel_success), Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(context, context.getText(R.string.cancel_failed), Toast.LENGTH_SHORT).show();
                }
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isrefresh = true;
                getJson();
            }
        });

        province_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, ProvinceWiseActivity.class);
                startActivity(intent);
            }
        });

        city_btn = view.findViewById(R.id.fragment_country_city_data);
        city_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collections.sort(citiesList, new Comparator<Cities>() {
                    @Override
                    public int compare(Cities o1, Cities o2) {
                        if (o1.getConfirmedCount() > o2.getConfirmedCount())
                            return -1;
                        else
                            return 1;
                    }
                });
                IStoreUtil.getInstance().setCitiesList(citiesList); // 把一个城市的省份信息全部保存，避免多次请求api

                Intent intent = new Intent(context, CityWiseActivity.class);
                startActivity(intent);
            }
        });

        iLocationUtil.startClient();
        getLocation();
        return view;
    }

    public void getLocation() {
        Handler pdCanceller = new Handler();
        Runnable progressRunnable = new Runnable() {
            @Override
            public void run() {
                if (iLocationUtil.getmBDLocation() != null) {
                    province = iLocationUtil.getmBDLocation().getProvince();
                    iLocationUtil.setCity(iLocationUtil.getmBDLocation().getCity());
                    iLocationUtil.setCountry(iLocationUtil.getmBDLocation().getCountry());
                    iLocationUtil.setProvince(iLocationUtil.getmBDLocation().getProvince());
                    city = iLocationUtil.city.substring(0, 2);
                    ((AppCompatActivity) requireActivity()).getSupportActionBar().setTitle(context.getText(R.string.covid_19_tracking) + "(" + iLocationUtil.getmBDLocation().getCity() + ")");
                    Log.i(context.toString(), "run: " + city);
                    getJson();
                } else {
                    province_btn.setClickable(false);
                    province_btn.setFocusable(false);
                    city_btn.setClickable(false);
                    city_btn.setFocusable(false);
                    Toast.makeText(context, context.getText(R.string.location_failed), Toast.LENGTH_SHORT).show();
                    progressDialog.cancel();
                }
            }
        };
        pdCanceller.postDelayed(progressRunnable, 3000);
    }

    public void showProgressDialog() {
        progressDialog = new ProgressDialog(context);
        progressDialog.show();
        progressDialog.setContentView(R.layout.progress_dialog);
        progressDialog.setCanceledOnTouchOutside(false);
        Objects.requireNonNull(progressDialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent); // 背景透明化
    }


    private void getJson() {
        Call<Country> call = ApiClient.getInstance().getApi().getAllArea();
        call.enqueue(new Callback<Country>() {
            @Override
            public void onResponse(Call<Country> call, Response<Country> response) {
                Log.i(context.toString(), "run: " + response.code());
                if (response.body() != null && response.body().getSuccess()) {
                    countryResultsList = response.body().getResults();
                    for (CountryResults countryResults : response.body().getResults()) {
                        if (countryResults.getProvinceName().equals(province)) {
                            provinceResult = countryResults;
                            IStoreUtil.getInstance().setCurrent_province(provinceResult);
                            citiesList = (ArrayList<Cities>) countryResults.getCities();
                            IStoreUtil.getInstance().setCitiesList(citiesList);
                            if (countryResultsList != null) {
                                results = new ArrayList<>();
                                for (CountryResults country : countryResultsList) {
                                    if (country.getCountryName().equals(iLocationUtil.getCountry())) {
                                        results.add(country);
                                    }
                                }
                                Collections.sort(results, new Comparator<CountryResults>() {
                                    @Override
                                    public int compare(CountryResults o1, CountryResults o2) {
                                        if (o1.getConfirmedCount() > o2.getConfirmedCount())
                                            return -1;
                                        else
                                            return 1;
                                    }
                                });
                                IStoreUtil.getInstance().setCountryResultsList(results); // 把一个国家的省份信息全部保存，避免多次请求api
                            }

                            Log.i(context.toString(), "run: get province success!");
                            break;
                        }
                    }

                    if (provinceResult != null && provinceResult.getCities() != null) {
                        for (Cities cities : provinceResult.getCities()) {
                            if(cities.getCityEnglishName() == null) {
                                cities.setCityEnglishName("Overseas import"); // 境外输入
                            }
                            else if (cities.getCityName().equals(city)) {
                                cityResult = cities;
                                querycity = cities.getCityEnglishName();
                                if(idbHelper.query(querycity)) {
                                    likeButton.setLiked(true);
                                }
                                else  {
                                    likeButton.setLiked(false);
                                }
                                Log.i(context.toString(), "run: get city success!");
                                fragment_country_CurrentConfirmed.setText(NumberFormat.getInstance().format(cityResult.getCurrentConfirmedCount()));
                                fragment_country_confirmed.setText(NumberFormat.getInstance().format(cityResult.getConfirmedCount()));
                                fragment_country_suspected.setText(NumberFormat.getInstance().format(cityResult.getSuspectedCount()));
                                fragment_country_Cured.setText(NumberFormat.getInstance().format(cityResult.getCuredCount()));
                                fragment_country_deaths.setText(NumberFormat.getInstance().format(cityResult.getDeadCount()));
                                Log.i(context.toString(), "onResponse: " + IDateUtil.getInstance().formatDate(provinceResult.getUpdateTime(), 2));
                                fragment_country_clock.setText(IDateUtil.getInstance().formatDate(provinceResult.getUpdateTime(), 2));
                                fragment_country_day.setText(IDateUtil.getInstance().formatDate(provinceResult.getUpdateTime(), 1));

                                fragment_country_piechart.clearChart();
                                fragment_country_piechart.addPieSlice(new PieModel("Current Confirmed", cityResult.getCurrentConfirmedCount(), Color.parseColor("#fbc233")));
                                fragment_country_piechart.addPieSlice(new PieModel("Suspected", cityResult.getSuspectedCount(), Color.parseColor("#08a045")));
                                fragment_country_piechart.addPieSlice(new PieModel("Deaths", cityResult.getDeadCount(), Color.parseColor("#f6404f")));
                                fragment_country_piechart.addPieSlice(new PieModel("Cured", cityResult.getCuredCount(), Color.parseColor("#FF03DAC5")));

                                if (isrefresh) {
                                    Toast.makeText(context, context.getText(R.string.data_refresh), Toast.LENGTH_SHORT).show();
                                }

                                province_btn.setClickable(true);
                                province_btn.setFocusable(true);
                                city_btn.setClickable(true);
                                city_btn.setFocusable(true);

                                fragment_country_piechart.startAnimation();

                                isOK = true;
                                progressDialog.cancel();
                                break;
                            }
                        }
                    }
                }
                if (!isOK) {
                    if(progressDialog.isShowing()) {
                        progressDialog.cancel();
                    }
                    province_btn.setClickable(false);
                    province_btn.setFocusable(false);
                    city_btn.setClickable(false);
                    city_btn.setFocusable(false);
                    Toast.makeText(context, context.getText(R.string.network_slow), Toast.LENGTH_SHORT).show();
                }
                swipeRefreshLayout.setRefreshing(false);
                isrefresh = false;
            }

            @Override
            public void onFailure(Call<Country> call, Throwable t) {
                Log.i(context.toString(), "onFailure: " + t.getCause());
                province_btn.setClickable(false);
                province_btn.setFocusable(false);
                city_btn.setClickable(false);
                city_btn.setFocusable(false);
                swipeRefreshLayout.setRefreshing(false);
                progressDialog.cancel();
                Toast.makeText(context, context.getText(R.string.network_slow), Toast.LENGTH_SHORT).show();
                isrefresh = false;
            }
        });
    }


}

